﻿using Net_SCADA;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.LinkLabel;

namespace WZXC_GBL_QUERY
{
    public partial class Form_QueryBoxWeight : Form
    {
      
        public Form_QueryBoxWeight()
        {
            InitializeComponent();
        }

        private void Form_BoxQueryWeight_Load(object sender, EventArgs e)
        {
            lst_BoxsDetail.Columns.Add("料框编号",200,HorizontalAlignment.Center);
            lst_BoxsDetail.Columns.Add("装载时间", 400, HorizontalAlignment.Center);
            lst_BoxsDetail.Columns.Add("料框重量", 200, HorizontalAlignment.Center);
        }


        private float LoadBoxList(DateTime starttime,DateTime endtime)
        {
            lst_BoxsDetail.Items.Clear();
            lbl_TotalBoxs.Text = "0";
            lbl_TotalWeight.Text = "0"; 
            DataTable dt=DBOperate.GetProcessBoxByTime(starttime,endtime);
            if(dt != null && dt.Rows.Count >0 ){ 
                float total = 0;
                for (int i = 0; i < dt.Rows.Count ; i++)
                {
                    string s =dt.Columns.Contains("weight")? dt.Rows[i]["weight"].ToString():"0";
                    lst_BoxsDetail.Items.Add(new ListViewItem( new string[] { dt.Rows[i]["box"].ToString(), dt.Rows[i]["loadtime"].ToString(), s }));
                    if(float.TryParse(s,out float x)) total+= x;
                }
                lbl_TotalBoxs.Text=dt.Rows.Count.ToString();    
                lbl_TotalWeight.Text=total.ToString();
            }
            return 0;
        }


        private void PrintBoxWeightDetail()
        {

            string pdfFilename = Application.StartupPath + "\\RecordData\\";
            if (!Directory.Exists(pdfFilename)) Directory.CreateDirectory(pdfFilename);
            pdfFilename += "boxweight.pdf";
            fd_PDF pdf = new fd_PDF(PdfPageOrientation.Portrait);
            int firstPagelines = 33;
            int nextPagelines = 40;
            int totalpages = 1;
            if (lst_BoxsDetail.Items.Count > firstPagelines)
            {
                totalpages = 1 + (lst_BoxsDetail.Items.Count - firstPagelines) / nextPagelines;
                if ((lst_BoxsDetail.Items.Count - firstPagelines) % nextPagelines != 0) totalpages += 1;
            }

           

            //打印第一页
            pdf.PagesAdd();
            //PrintTitle(pdf, "料框统计", 0);
            PrintLog(pdf);
            PrintGroup(pdf,"料框重量统计",new RectangleF(pdf.Margin, 58, pdf.PageWidth - pdf.Margin * 2, 34 + 24 * 2));
            float w = (pdf.PageWidth - pdf.Margin * 2 - 5 * 4) / 4;
            float top = 58 + 34;
            PrintContent(pdf, new RectangleF(pdf.Margin + 4 , top, w, 20), "开始时间", true);//打印的信息名称
            PrintContent(pdf, new RectangleF(pdf.Margin + 4 + (w + 4), top, w, 20), dp_timestart.Value.ToString("yyyy-MM-dd HH:mm:ss"), false);//打印内容
            PrintContent(pdf, new RectangleF(pdf.Margin + 4 + (w + 4) * 2, top, w, 20), "结束时间", true);//打印的信息名称
            PrintContent(pdf, new RectangleF(pdf.Margin + 4 + (w + 4) * 3, top, w, 20), dp_timeend.Value.ToString("yyyy-MM-dd HH:mm:ss"), false);//打印内容
            top += 24;
            PrintContent(pdf, new RectangleF(pdf.Margin + 4, top, w, 20), "料框总计", true);//打印的信息名称
            PrintContent(pdf, new RectangleF(pdf.Margin + 4 + (w + 4), top, w, 20), lbl_TotalBoxs.Text, false);//打印内容
            PrintContent(pdf, new RectangleF(pdf.Margin + 4 + (w + 4) * 2, top, w, 20), "累计重量", true);//打印的信息名称
            PrintContent(pdf, new RectangleF(pdf.Margin + 4 + (w + 4) * 3, top, w, 20), lbl_TotalWeight.Text, false);//打印内容

            top += 44;
            PrintContent(pdf, new RectangleF(pdf.Margin , top, pdf.PageWidth - pdf.Margin * 2, 20), "单框料重详细数据", false);//打印内容
            top += 24;
            float h = (pdf.PageHeight - pdf.Margin * 3 - nextPagelines) / (nextPagelines+1);
            if (totalpages == 1)
                PrintListTabel(pdf, lst_BoxsDetail, top, h, 0, lst_BoxsDetail.Items.Count);
            else
            {
                PrintListTabel(pdf, lst_BoxsDetail, top, h, 0, firstPagelines);
                PrintTail(pdf, 1, totalpages);
                for (int i = 1; i < totalpages; i++)
                {
                    pdf.PagesAdd();
                    PrintLog(pdf);
                    PrintListTabel(pdf, lst_BoxsDetail, 58, h, firstPagelines + nextPagelines * (i - 1), i < (totalpages - 1) ? nextPagelines : lst_BoxsDetail.Items.Count - firstPagelines - nextPagelines * (i - 1));
                    PrintTail(pdf, i + 1, totalpages);
                }
            }
            pdf.SaveToPDF(pdfFilename);
            foreach (PdfPageBase page in pdf.Doc.Pages)
            {
                pdf.PageRemove(page);
            }
            pdf.Doc = null;
            System.Diagnostics.Process.Start(pdfFilename);
            
        }


        /// <summary>
        /// 打印一个listview的部分内容
        /// </summary>
        /// <param name="lv">需要打印的表</param>
        /// <param name="top">打印的上端</param>
        /// <param name="h">打印的行高</param>
        /// <param name="index">打印的数据开始位置</param>
        /// <param name="counts">打印的数据数量</param>
        private void PrintListTabel(fd_PDF pdf, ListView lv,float top,float h,int index,int counts)
        {
            PdfPen pen = pdf.PenColor(Color.Black, 1f);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(new Font("宋体", 12f, FontStyle.Regular), true);

            float[] x = new float[lv.Columns.Count+1];//存放纵线的x坐标线
            x[0] = pdf.Margin;
            for (int i = 0; i < lv.Columns.Count; i++)
            {
                //打印竖线和内容
                pdf.DrawLine(pen, new PointF(x[i], top), new PointF(x[i], top + h * (counts + 1)));//打印竖线
                pdf.DrawString(lv.Columns[i].Text, fontTitle, brush, new PointF(x[i] + 2, top));//打印表头
                x[i+1] =x[i]+ (pdf.PageWidth - pdf.Margin * 2) * ((float)lv.Columns[i].Width / (float)lv.Width);//计算下一个线的x坐标
            }
            pdf.DrawLine(pen, new PointF(pdf.PageWidth-pdf.Margin, top), new PointF(pdf.PageWidth-pdf.Margin, top + h * (counts + 1)));//打印最后一个竖线

            pdf.DrawLine(pen, new PointF(pdf.Margin, top), new PointF(pdf.PageWidth - pdf.Margin, top));//打印表头上的横线
            float y = top+h;
            for (int i = 0; i < counts && i+index<lv.Items.Count; i++)
            {
                pdf.DrawLine(pen, new PointF(pdf.Margin, y), new PointF(pdf.PageWidth - pdf.Margin, y));//打印数据行上的横线
                for (int j = 0; j < lv.Columns.Count ; j++)
                {
                    pdf.DrawString(lv.Items[i+index].SubItems[j].Text, fontTitle, brush, new PointF(x[j] + 2, y));//打印数据
                }
                y += h;
            }
            pdf.DrawLine(pen, new PointF(pdf.Margin, y), new PointF(pdf.PageWidth - pdf.Margin, y));//打印表头上的横线
        }

        private void PrintGroup(fd_PDF pdf, string groupName, RectangleF rectangle)
        {
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("微软雅黑", 14f, FontStyle.Regular), true);
            PdfSolidBrush brush = pdf.BrushColor(Color.WhiteSmoke);
            PdfPen pen = pdf.PenColor(Color.LightGray);
            pdf.DrawRectangle(pen, rectangle);
            pdf.DrawRectangle(pen, brush, new RectangleF(rectangle.Left + 4, rectangle.Top + 4, rectangle.Width - 8, 25));
            brush = pdf.BrushColor(Color.Black);
            pdf.DrawString(groupName, font, brush, new PointF(rectangle.Left + 8, rectangle.Top + 6.5f));
        }
        private void PrintContent(fd_PDF pdf, RectangleF rectangle, string content, bool istitle, PdfTextAlignment align = PdfTextAlignment.Left)
        {
            PrintContent(pdf, rectangle, content, 12f, Color.DarkSlateGray, Color.WhiteSmoke, istitle, align);
        }
        private void PrintContent(fd_PDF pdf, RectangleF rectangle, string content, float fontsize, Color txtColor, Color bgColor, bool istitle, PdfTextAlignment align = PdfTextAlignment.Left)
        {
            PdfSolidBrush txtbrush = pdf.BrushColor(txtColor);
            PdfSolidBrush bgbrush = pdf.BrushColor(bgColor);
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("微软雅黑", fontsize, FontStyle.Regular), true);
            PdfPen pen = pdf.PenColor(Color.LightGray);
            if (istitle)
            {
                pdf.DrawRectangle(pen, bgbrush, rectangle);
            }
            else
            {
                pdf.DrawRectangle(pen, rectangle);
            }
            float div = (rectangle.Height - fontsize) / 2 - 2;
            pdf.DrawString(content, font, txtbrush, new PointF(rectangle.Left + 4, rectangle.Top + div));
        }

        private void PrintTitle(fd_PDF pdf, string title, int lcr)
        {
            Font ft = new Font("微软雅黑", 16f, FontStyle.Regular);
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(ft, true);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            float w = pdf.GetTextSize(ft, title).Width;
            float left = pdf.Margin;
            if (lcr == 1) left = (pdf.PageWidth - w) / 2;
            if (lcr == 2) left = pdf.PageWidth - w;
            pdf.DrawString(title, fontTitle, brush, new PointF(left, pdf.Margin));
        }
        private void PrintLog(fd_PDF pdf)
        {
            //打印LOG
            string logfile = Application.StartupPath + @"\log.bmp";
            if (!File.Exists(logfile)) return;
            Image img = Image.FromFile(logfile);
            pdf.DrawImage(img, new RectangleF(pdf.PageWidth - img.Width - pdf.Margin, -10 + pdf.Margin, img.Width, img.Height));
        }

        private void PrintTail(fd_PDF pdf, int index, int total)
        {
            Font ft = new Font("宋体", 9f, FontStyle.Regular);
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(ft, true);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            StringBuilder sb = new StringBuilder().Append("第").Append(index).Append("页 共").Append(total).Append("页");
            float w = pdf.GetTextSize(ft, sb.ToString()).Width;
            float left = pdf.PageWidth - pdf.Margin - w;
            pdf.DrawString(sb.ToString(), fontTitle, brush, new PointF(left, pdf.PageHeight - pdf.Margin + 2f));
        }
        private void btn_Query_Click(object sender, EventArgs e)
        {
            DateTime st = dp_timestart.Value;
            DateTime et = dp_timeend.Value;
            if(st>et)
            {
                st=dp_timeend.Value;
                et=dp_timestart.Value;  
            }
            LoadBoxList(st, et);
        }

        private void btn_Print_Click(object sender, EventArgs e)
        {
            PrintBoxWeightDetail();
        }
    }
}
